<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';

import { h, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message, Modal } from 'ant-design-vue';

import { Apis } from '#/api';

const emit = defineEmits(['success']);

export interface ResetPasswordModalState {
  userId: string;
  nickname: string;
}

const data = ref<ResetPasswordModalState>({
  userId: '',
  nickname: '',
});

const form = reactive({
  type: 'modify',
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const formRef = ref<FormInstance>();

const isLoading = ref(false);

const rules: Record<string, Rule[]> = {
  type: [{ required: true, message: '请选择操作类型' }],
  oldPassword: [{ required: true, message: '请填写旧密码' }],
  newPassword: [{ required: true, message: '请填写新密码' }],
  confirmPassword: [
    { required: true, message: '请再次确认密码' },
    {
      validator: (_rule: Rule, value: string) =>
        value === form.newPassword
          ? Promise.resolve()
          : Promise.reject(new Error('两次输入的密码不一致')),
    },
  ],
};

const [BaseModal, baseModalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = baseModalApi.getData<ResetPasswordModalState>();
    }
  },
  onConfirm: onSubmit,
});

async function onSubmit() {
  await formRef.value!.validate();

  try {
    isLoading.value = true;
    if (form.type === 'modify') {
      await Apis.system.user.updatePwd({
        pathParams: {
          id: data.value.userId,
        },
        data: {
          oldPwd: form.oldPassword,
          newPwd: form.newPassword,
        },
      });
    }

    if (form.type === 'reset') {
      const res = await Apis.system.user.resetPwd({
        pathParams: {
          id: data.value.userId,
        },
      });

      Modal.success({
        title: '重置密码成功',
        content: h('div', {}, [
          h('p', `新密码：${res.password}，请及时通知用户登录系统修改密码`),
        ]),
      });
    }

    message.success({
      content: `操作成功`,
    });

    baseModalApi.close();
    emit('success');
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    isLoading.value = false;
  }
}
</script>
<template>
  <BaseModal
    :confirm-loading="isLoading"
    class="w-[600px]"
    title="修改/重置用户密码"
  >
    <a-form
      ref="formRef"
      :label-col="{ style: 'width: 120px' }"
      :model="form"
      :rules="rules"
      class="grid-cols-1"
      label-class="w-full"
      layout="horizontal"
    >
      <a-form-item label="用户昵称">
        <a-input
          v-model:value="data.nickname"
          class="w-full"
          placeholder=""
          readonly
        />
      </a-form-item>

      <a-form-item label="操作类型" name="type">
        <a-radio-group v-model:value="form.type" class="w-full">
          <a-radio value="modify">修改密码</a-radio>
          <a-radio value="reset">重置密码</a-radio>
        </a-radio-group>
      </a-form-item>

      <template v-if="form.type === 'modify'">
        <a-form-item label="原密码" name="oldPassword">
          <a-input-password
            v-model:value="form.oldPassword"
            placeholder="请填写原密码"
          />
        </a-form-item>

        <a-form-item label="新密码" name="newPassword">
          <a-input-password
            v-model:value="form.newPassword"
            placeholder="请填写新密码"
          />
        </a-form-item>

        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password
            v-model:value="form.confirmPassword"
            placeholder="请确认新密码"
          />
        </a-form-item>
      </template>
    </a-form>
  </BaseModal>
</template>
